<script setup>
import {ref, nextTick} from 'vue';
import ChatMessages from './chatMessages.vue';
import ChatInput from './chatInput.vue';
import ChatHistory from './chatHistory.vue';
import SelectAI from '@/components/SelectAI.vue';
import {ElTooltip} from 'element-plus';
import {getChatMessages, sendChatMessage} from '@/api/chat';
import {useTokenStore} from '@/stores/token';
import {useAiSettingStore} from '@/stores/aiSetting';

const tokenStore = useTokenStore();
const store = useAiSettingStore();
const currentConversation = ref([]);
const currentChatId = ref(null);
const childRef = ref(null);
// 添加消息到当前会话
const addMessage = async (message) => {
  // 添加用户消息
  currentConversation.value.push({
    ...message,
    displayedContent: message.content
  });

  // 创建AI消息对象
  const aiMsg = {
    id: `ai-${Date.now()}`,
    role: 'assistant',
    content: '',
    displayedContent: '',
    loading: true,
    files: []
  };
  currentConversation.value.push(aiMsg);

  try {
    // 准备发送给后端的数据
    const data = {
      prompt: message.content,
      chatId: currentChatId.value || generateChatId(),
      model: store.model,
      files: message.files.map(f => f.file)
    };

    // 如果没有chatId，设置当前chatId
    if (!currentChatId.value) {
      currentChatId.value = data.chatId;
    }

    // 发送请求并获取响应流，传递token
    const reader = await sendChatMessage(data, tokenStore.token);  // 直接获取 reader

    const decoder = new TextDecoder('utf-8');
    let accumulatedContent = ''; // 累积内容

    // 开始输出内容
    aiMsg.loading = false;

    while (true) {
      try {
        const {value, done} = await reader.read();
        if (done) break;

        // 累积新内容
        accumulatedContent += decoder.decode(value);

        await nextTick(() => {
          // 更新消息，使用累积的内容
          const updatedMessage = {
            ...aiMsg,
            displayedContent: accumulatedContent  // 使用累积的内容
          }
          const lastIndex = currentConversation.value.length - 1
          currentConversation.value.splice(lastIndex, 1, updatedMessage)
        })
      } catch (readError) {
        console.error('读取流错误:', readError);
        break;
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    // 更新错误消息
    await nextTick(() => {
      const updatedMessage = {
        ...aiMsg,
        displayedContent: '请求失败: ' + error.message,
        loading: false
      }
      const lastIndex = currentConversation.value.length - 1
      currentConversation.value.splice(lastIndex, 1, updatedMessage)
    })
  } finally {
    // 确保loading状态被设置为false
    await nextTick(() => {
      const lastIndex = currentConversation.value.length - 1
      if (lastIndex >= 0) {
        currentConversation.value[lastIndex].loading = false
      }
    })
  }
  if(childRef.value){
    await childRef.value.fetchSessions();
  }
};

// 生成chatId的函数
const generateChatId = () => {
  return 'chat-' + Math.random().toString(36).substr(2, 9);
};

// 新建会话
const handleNewConversation = (conversation) => {
  currentChatId.value = conversation.chatId;
  currentConversation.value = [];
};

// 切换会话
const handleSwitchConversation = async (conversation) => {
  currentChatId.value = conversation.chatId;
  try {
    const response = await getChatMessages("chat", conversation.chatId);
    currentConversation.value = response.data.map(msg => ({
      id: msg.id,
      role: msg.role.toLowerCase(),
      content: msg.content,
      displayedContent: msg.content,
      loading: false,
      files: []
    }));
  } catch (error) {
    console.error('加载会话消息失败:', error);
    currentConversation.value = [];
  }
};

// 删除所有会话
const handleDeleteAllConversations = () => {
  currentChatId.value = null;
  currentConversation.value = [];
};

// 添加处理会话删除事件
const handleConversationDeleted = (chatId) => {
  // 如果删除的是当前会话，重置状态
  if (currentChatId.value === chatId) {
    currentChatId.value = null;
    currentConversation.value = [];
  }
};

</script>

<template>
  <div class="main-container">
    <div class="chat-container">
      <div class="chat-header">
        <div class="chat-title">{{ $t("assistant") }}</div>
        <div class="chat-subtitle">{{ $t("help") }}</div>
        <ElTooltip content="选择您想使用的AI" placement="right">
          <SelectAI></SelectAI>
        </ElTooltip>
      </div>
      <div class="message-container">
        <ChatMessages :messages="currentConversation"/>
      </div>
      <div class="input-container">
        <ChatInput
            @send-message="addMessage"
            :chatId="currentChatId"
        />
      </div>
    </div>
    <div class="history-container">
      <ChatHistory
          ref="childRef"
          @new-conversation="handleNewConversation"
          @switch-conversation="handleSwitchConversation"
          @delete-all="handleDeleteAllConversations"
          @delete-conversation="handleConversationDeleted"
      />
    </div>
  </div>
</template>

<style scoped>
.main-container {
  display: flex;
  height: 100vh;
  background-color: var(--bgcolor);
  margin-left: 6vw;

}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--wrap-bg);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
  background-color: var(--wrap-bg);
  display: flex;
  align-items: center;
  z-index: 2;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.chat-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--cart-text);
}

.chat-subtitle {
  font-size: 14px;
  color: var(--h4-color);
  margin-left: 20px;
  margin-right: 20px;
}

.message-container {
  margin-left: 100px;
  margin-right: 150px;
  flex: 1;
  overflow-y: auto;
  padding: 30px;
  background-color: var(--wrap-bg);
}

.input-container {
  margin-left: 50px;
  margin-right: 100px;
  padding: 20px;
  background: var(--wrap-bg);
  position: sticky;
  bottom: 0;
  z-index: 1;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
}

.history-container {
  background: var(--wrap-bg);
  display: flex;
  flex-direction: column;
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.05);
  z-index: 2;
  transition: width 0.3s ease;
}
</style>